package com.jfirer.redisserver;

import com.jfirer.jnet.common.api.*;
import com.jfirer.jnet.common.internal.JnetWorkerImpl;
import com.jfirer.jnet.common.util.ChannelConfig;
import com.jfirer.jnet.server.AioServer;

public class JfireRedisServer implements RedisServer
{
    private final RedisCore   redisCore = new RedisCoreImpl();
    private       AioServer   aioServer;
    private       WorkerGroup workerGroup;

    public JfireRedisServer()
    {
        JnetWorker jnetWorker = new JnetWorkerImpl("redis-singleThread");
        ((JnetWorkerImpl) jnetWorker).start();
        workerGroup = () -> jnetWorker;
    }

    public static void main(String[] args)
    {
        new JfireRedisServer().start(6378);
    }

    public void start(int port)
    {
        final ChannelConfig config = new ChannelConfig();
        config.setPort(port);
        aioServer = new AioServer(config, new ChannelContextInitializer()
        {
            @Override
            public void onChannelContextInit(ChannelContext channelContext)
            {
                Pipeline pipeline = channelContext.pipeline();
                pipeline.add(new ResponseEncoder());
                pipeline.add(new CommandDecoder(config.getAllocator()));
                pipeline.add(new CommandHandler(redisCore),workerGroup);
            }
        });
        aioServer.start();
    }

    @Override
    public void close()
    {
        aioServer.shutdown();
    }

    @Override
    public RedisCore getRedisCore()
    {
        return redisCore;
    }
}
